import React, { Component } from 'react';

import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, Table } from 'antd';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import router from 'umi/router';
import Ellipsis from '../../../components/Ellipsis';

import { findDicByCode, getDicByKey, getDictOptionsByCode } from '@/support/common';
import PropTypes from 'prop-types';
import MaskText from '@/components/MaskText';

@connect((state: any) => ({
  vehicleInfoQuery: state.vehicleInfoQuery,
  loading: state.loading.effects['vehicleInfoQuery/postFetchPage'],
}))
class Page extends Component<any, any> {
  // searchRef: FormInstance;
  static contextTypes = {
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      brand: [],
      series: [],
      type: [],
      dealer: [],
      judgeData: [],
      extendStatus: false,
      formValues: {},
      pagination: {
        page: 0,
        size: 10,
      },
      //  page size
    };
  }

  // 重置品牌
  setBrand = () => {
    this.searchForm.current.resetFields(['brandId', 'seriesId', 'styleId', 'dealerNo']);
    this.props.dispatch({
      type: 'vehicleInfoQuery/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: e => {
        this.setState({
          brand: e.data.map(e => ({
            label: e.brandName,
            value: e.brandCode,
          })),
          series: [],
          type: [],
          dealer: [],
        });
      },
    });
  };

  // 重置车系
  setSeries = () => {
    this.searchForm.current.resetFields(['seriesId', 'styleId']);

    this.setState({ series: [], type: [] });
    const brandId = this.searchForm.current.getFieldValue('brandId');
    brandId &&
      this.props.dispatch({
        type: 'vehicleInfoQuery/getDataWithRes',
        payload: {
          url: '/common/vehicle/getserieslist',
          brandId,
        },
        callback: e => {
          this.setState({
            series: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  };

  // 重置车型
  setType = () => {
    this.searchForm.current.resetFields(['styleId']);
    this.setState({ type: [] });
    const brandId = this.searchForm.current.getFieldValue('brandId');
    const seriesId = this.searchForm.current.getFieldValue('seriesId');
    brandId &&
      seriesId &&
      this.props.dispatch({
        type: 'vehicleInfoQuery/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: e => {
          this.setState({
            type: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
        // callback: e => {
        //   this.searchItems.find(e => e.key === 'type').selectOptions = e.data.map(e => ({
        //     label: e.name,
        //     value: e.code,
        //   }));
        //   this.setState({});
        // },
      });
  };

  // 设置经销商
  setDealer = () => {
    this.searchForm.current.resetFields(['dealerNo']);
    // this.searchItems.find(e => e.key === 'dealer').selectOptions = [];
    const brandId = this.searchForm.current.getFieldValue('brandId');
    this.setState({ dealer: [] });
    brandId &&
      this.props.dispatch({
        type: 'vehicleInfoQuery/getDataWithRes',
        payload: {
          url: '/common/vehicle/getdealerlist',
          brandId,
        },
        callback: e => {
          this.setState({
            dealer: e.data.map(e => ({
              label: e.name,
              value: e.code,
            })),
          });
        },
      });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, pagination } = this.state;
    this.unlisten = this.props.history.listen((location: any, action: any) => {
      const { sourcePage } = location;
      let values = {
        ...pagination,
      };
      if (sourcePage === 'vehicleInfoQueryDetail') {
        //  详情返回
        const tempValues = sessionStorage.getItem('vehicleInfoQuerySearchValues');
        values = {
          ...values,
          ...(JSON.parse(tempValues) || {}),
        };
        this.setState({
          extendStatus: true,
        });
      }
      const { page, size, ...rest } = values;
      this.setState(
        {
          formValues: {
            ...formValues,
            ...rest,
          },
          pagination: {
            page,
            size,
          },
        },
        () => {
          const { formValues, pagination } = this.state;
          this.searchForm.current.setFieldsValue({
            ...formValues,
          });
          dispatch({
            type: 'vehicleInfoQuery/postFetchPage',
            payload: { url: '/vehicle/vehiclefindbypage', ...formValues, ...pagination },
          });
        },
      );
    });

    this.setBrand();

    // dispatch({
    //   type: 'vehicleInfoQuery/getDataWithRes',
    //   payload: { url: '/basedata/findredisdata' },
    //   callback: response => {
    //     this.setState({
    //       judgeData: response,
    //     });
    //   },
    // });
  }

  onSource = (page, size, args) =>
    new Promise(async resolve => {
      const res = await this.props.dispatch({
        type: 'vehicleInfoQuery/postFetchPage',
        payload: {
          url: '/vehicle/vehiclefindbypage',
          page: page - 1,
          size: size,
          ...args,
        },
      });
      if (res && res.statusCode === '0') {
        resolve({
          total: res.data.pagination.total,
          data: res.data.list,
        });
      } else {
        resolve({
          total: 0,
          data: [],
        });
      }
    });
  //保存record信息
  handleEditData = (vehicle: any) => {
    const { formValues, pagination } = this.state;
    const searchValues = {
      ...formValues,
      ...pagination,
    };
    sessionStorage.setItem('vehicleInfoQuerySearchValues', JSON.stringify(searchValues));
    this.props.dispatch({
      type: 'vehicleInfoQuery/setVehicleInfo',
      payload: {
        ...vehicle,
      },
    });
    sessionStorage.setItem('vehicleInfo', JSON.stringify(vehicle));
    router.push('/connectPlat/vehicleInfoQuery/vehicleInfoQueryDetail');
  };

  handleFormReset = (fields: any) => {
    this.searchForm.current.setFieldsValue({});
    this.setState({
      formValues: {},
      pagination: {
        page: 0,
        size: 10,
      },
    });
  };

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    const params = {
      ...formValues,
      page: current - 1,
      size: pageSize,
      ...filters,
    };
    this.setState(
      {
        pagination: {
          page: current - 1,
          size: pageSize,
        },
      },
      () => {
        dispatch({
          type: 'vehicleInfoQuery/postFetchPage',
          payload: { url: '/vehicle/vehiclefindbypage', ...params },
        });
      },
    );
  };

  render() {
    const {
      vehicleInfoQuery: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { brand, series, type, dealer, extendStatus } = this.state;
    const { context } = this;
    const realNameStatusOptions = getDictOptionsByCode(this.context.dicData, 'RealNameStatusList');
    const enrollStatusOptions = getDictOptionsByCode(this.context.dicData, 'vehicleEnrollStatus');
    const vhlTypeOptions = getDictOptionsByCode(this.context.dicData, 'fenceVhlType');
    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        key: 'brandId',
        selectOptions: brand,

        onChange: () => {
          this.setSeries();
          this.setDealer();
        },
      },
      {
        title: '车系',
        type: 'select',
        key: 'seriesId',
        selectOptions: series,
        onChange: () => this.setType(),
      },
      {
        title: '车型',
        type: 'select',
        key: 'styleId',
        selectOptions: type,
      },

      {
        title: 'VIN码',
        type: 'input',
        key: 'vin',
        rules: [
          {
            required: false,
            message: '请输入10-17的英文和数字',
            min: 10,
            max: 17,

            pattern: '^[a-zA-Z0-9]*$',
          },

          // { pattern: '^[a-zA-Z0-9]*$', message: '只支持数字、英文，不区分大小写，请正确输入' },
        ],
      },
      {
        title: '车牌号码',
        type: 'input',
        key: 'licence',
      },

      {
        title: '经销商',
        type: 'select',
        key: 'dealerNo',
        selectOptions: dealer,
      },
      {
        title: '激活类型',
        type: 'select',
        key: 'vhlType',
        selectOptions: vhlTypeOptions || [],
      },
      {
        title: '激活状态',
        type: 'select',
        key: 'enrollStatus',
        selectOptions: enrollStatusOptions || [],
      },
      {
        title: '实名认证状态',
        type: 'select',
        key: 'realNameStatus',
        selectOptions: realNameStatusOptions || [],
      },
      {
        title: '网联类型',
        type: 'select',
        key: 'carSpt',
        selectOptions: [
          { value: '1', label: '手机' },
          { value: '0', label: '传统' },
        ],
      },
    ];
    const columns = [
      {
        title: 'VIN码',
        dataIndex: 'vin',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '品牌',
        dataIndex: 'brandName',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '车系',
        dataIndex: 'seriesName',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '车型',
        dataIndex: 'styleName',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '车型编码',
        dataIndex: 'styleId',
      },
      // {
      //   title: '车辆类型',
      //   dataIndex: '',
      // },
      {
        title: '车牌号码',
        dataIndex: 'licence',
        render(val: any) {
          return <MaskText text={val} type="plate" />;
        },
      },
      {
        title: '经销商',
        dataIndex: 'dealerName',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '网联类型',
        dataIndex: 'carSpt',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text && text === '1' ? '手机' : '传统'}
          </Ellipsis>
        ),
      },
      {
        title: '集团企业',
        dataIndex: 'groupId',
      },
      {
        title: '激活类型',
        dataIndex: 'vhlType',
        render: (text: any) =>
          text ? (
            <Ellipsis length={20} tooltip>
              {getDicByKey(context.dicData, 'fenceVhlType', `${text}`)}
            </Ellipsis>
          ) : (
            ''
          ),
      },
      {
        title: '激活状态',
        dataIndex: 'enrollStatus',
        render: (text: any) =>
          text !== null ? (
            <Ellipsis length={20} tooltip>
              {getDicByKey(context.dicData, 'vehicleEnrollStatus', `${text}`)}
            </Ellipsis>
          ) : (
            ''
          ),
      },
      {
        title: '实名认证状态',
        dataIndex: 'realNameStatus',
        render: (text: any) =>
          text ? (
            <Ellipsis length={20} tooltip>
              {getDicByKey(context.dicData, 'RealNameStatusList', `${text}`)}
            </Ellipsis>
          ) : (
            ''
          ),
      },
      {
        title: '入库时间',
        dataIndex: 'createDate',
      },
      {
        title: '车机编号',
        dataIndex: 'pdsn',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: 'TBOX编号',
        dataIndex: 'tbox',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: 'ICCID',
        dataIndex: 'iccid',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        render: (text: any) =>
          text ? (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          ) : (
            ''
          ),
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text: any, record: any) => {
          return <a onClick={() => this.handleEditData(record)}>详情</a>;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    //设置实名认证状态
    (() => {
      const nameStatus = findDicByCode(this.context.dicData, 'RealNameStatusList');

      searchItems.find(e => e.key === 'realNameStatus').selectOptions = nameStatus.map(a => ({
        label: a.dictValue,
        value: a.dictKey,
      }));
    })();
    //设置激活状态
    (() => {
      const activateState = findDicByCode(this.context.dicData, 'vehicleEnrollStatus');
      activateState.sort((a, b) => a.dictKey - b.dictKey);

      searchItems.find(e => e.key === 'enrollStatus').selectOptions = activateState.map(a => ({
        label: a.dictValue,
        value: a.dictKey,
      }));
    })();

    //设置激活类型
    (() => {
      const vehicleType = findDicByCode(this.context.dicData, 'fenceVhlType');

      searchItems.find(e => e.key === 'vhlType').selectOptions = vehicleType.map(a => ({
        label: a.dictValue,
        value: a.dictKey,
      }));
    })();
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            isExtend={extendStatus}
            fetchParams={{
              type: 'vehicleInfoQuery/postFetchPage',
              url: '/vehicle/vehiclefindbypage',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            // handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
          <Table
            size={'small'}
            rowKey={record => record.id}
            dataSource={list || []}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content' }}
          />
        </Card>
      </div>
    );
  }
}

export default Page;
